package com.example.fileupload.controller;

import com.example.common.entity.Result;
import com.example.fileupload.entity.FileChunk;
import com.example.fileupload.entity.FileRecord;
import com.example.fileupload.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author cc
 * @classname FileController
 * @description TODO
 * @date 2022/8/14 10:50
 */
@Api(tags = "文件上传")
@RestController
@RequestMapping("file")
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation("获取文件列表")
    @GetMapping("/files")
    public Result<List<FileRecord>> getFiles() {
        return Result.ok(fileService.getFiles());
    }

    @ApiOperation("检查文件MD5(文件MD5若已存在进行秒传)")
    @GetMapping("/check-file")
    public Result<Object> checkFileMd5(String md5, String fileName) {
        return fileService.checkFileMd5(md5, fileName);
    }

    @ApiOperation("分片上传/断点续传")
    @PostMapping(value = "/chunk-upload")
    public Result<String> chunkUpload(FileChunk fileChunk) {
        return Result.ok(null, fileService.chunkUpload(fileChunk));
    }

    @ApiOperation("断点续传完成后上传文件信息进行入库操作")
    @PostMapping("/save")
    public Result<String> saveFile(@RequestBody FileRecord fileRecord) {
        return Result.ok(null, fileService.saveFile(fileRecord));
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/{id}")
    public Result<String> download(HttpServletRequest request, HttpServletResponse response,
                                   @PathVariable Long id) {
        return Result.ok(null, fileService.download(request, response, id));
    }
}
